package com.apache.ius.common;

import com.apache.client.common.SmsUtil;
import com.apache.database.constant.SystemTools;
import com.apache.tools.ConfigUtil;
import com.apache.tools.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 系统-通用操作工具类
 */
public class CommonUtils {
    private static Logger log = LoggerFactory.getLogger(CommonUtils.class);
    private static final String file_config = "config.properties";//系统配置文件
    private static String sysEname;
    static {
        sysEname = getConfigVal("sysEname");
    }

    public static String getSysEname() {
        if(StrUtil.isNull(sysEname)){
            sysEname = getConfigVal("sysEname");
        }
        return sysEname;
    }
    /**
     * 添加内容到本系统缓存内
     * @param cacheKey 缓存key
     * @param object 存储数据
     * @return
     */
    public static boolean addCache(String cacheKey,Object object){
        String spaceName = sysEname+"_"+cacheKey;
        boolean flag = SystemTools.getInstance().getCache(spaceName).createCacheObject(cacheKey,object);
        return flag;
    }

    /**
     * 添加内容到本系统缓存内
     * @param cacheKey 缓存key
     * @param object 存储数据
     * @param expireTime 过期时间（-1永久）单位是秒
     * @return
     */
    public static boolean addCache(String cacheKey,Object object,int expireTime){
        String spaceName = sysEname+"_"+cacheKey;
        boolean flag = SystemTools.getInstance().getCache(spaceName).createCacheObject(cacheKey,object,expireTime);
        return flag;
    }

    /**
     * 添加内容到本系统缓存内
     * @param spaceName 缓存空间
     * @param cacheKey 缓存key
     * @param object 存储数据
     * @param expireTime 过期时间（-1永久）单位是秒
     * @return
     */
    public static boolean addCache(String spaceName,String cacheKey,Object object,int expireTime){
//        String spaceName = sysEname+"_"+cacheKey;
        boolean flag = SystemTools.getInstance().getCache(spaceName).createCacheObject(cacheKey,object,expireTime);
        return flag;
    }
    /**
     * 获取本系统指定缓存key的内容
     * @param cacheKey 缓存key
     * @return
     */
    public static Object getCache(String cacheKey){
        String spaceName = sysEname+"_"+cacheKey;
        Object object = SystemTools.getInstance().getCache(spaceName).getCacheObjectByKey(cacheKey);
        return object;
    }
    /**
     * 获取本系统指定缓存key的内容
     * @param spaceName 缓存空间
     * @param cacheKey 缓存key
     * @return
     */
    public static Object getCache(String spaceName,String cacheKey){
//        String spaceName = sysEname+"_"+cacheKey;
        Object object = SystemTools.getInstance().getCache(spaceName).getCacheObjectByKey(cacheKey);
        return object;
    }

    /**
     * 获取本系统指定应用app_config配置信息
     * @param typeKey 配置类型标识
     * @return
     */
    public static Object getCacheByAppConfig(String typeKey){
        String key = "app_config";
        String spaceName = sysEname+"_"+key;
        log.info("-");
        log.info("从缓存["+spaceName+"]中，读取["+key+"]下的["+typeKey+"]类型配置....");
        Object object = SystemTools.getInstance().getCache(spaceName).getCacheObjectByKey(key);
        if(object!=null){
            Map<String,Object> appConfigCache = (Map<String,Object>)object;
            if(appConfigCache!=null && appConfigCache.containsKey(typeKey)) {
                Map<String, Map> confMap = (Map) appConfigCache.get(typeKey);
                Iterator<Map.Entry<String,Map>> iter = confMap.entrySet().iterator();
                log.info("|********************["+sysEname+"]缓存的[sys_app_config]配置信息 start *******************************|");
                while (iter.hasNext())
                {
                    Map.Entry<String,Map> entry = iter.next();
                    Map value = (Map)entry.getValue();
                    log.info(" "+entry.getKey()+"->"+value);
                }
                log.info("|********************["+sysEname+"]缓存的[sys_app_config]配置信息 end ********************************|");
                log.info("-");
                return confMap;
            }
        }
        log.info("从缓存["+spaceName+"]中，读取["+key+"]下的["+typeKey+"]类型配置失败！！！");
        return null;
    }
    public static Object getCacheByAppConfig(String typeKey,String sysEname){
        String key = "app_config";
        String spaceName = sysEname+"_"+key;
        log.info("-");
        log.info("从缓存["+spaceName+"]中，读取["+key+"]下的["+typeKey+"]类型配置....");
        Object object = SystemTools.getInstance().getCache(spaceName).getCacheObjectByKey(key);
        if(object!=null){
            Map<String,Object> appConfigCache = (Map<String,Object>)object;
            if(appConfigCache!=null && appConfigCache.containsKey(typeKey)) {
                Map<String, Map> confMap = (Map) appConfigCache.get(typeKey);
                Iterator<Map.Entry<String,Map>> iter = confMap.entrySet().iterator();
                log.info("|********************["+sysEname+"]缓存的[sys_app_config]配置信息 start *******************************|");
                while (iter.hasNext())
                {
                    Map.Entry<String,Map> entry = iter.next();
                    Map value = (Map)entry.getValue();
                    log.info(" "+entry.getKey()+"->"+value);
                }
                log.info("|********************["+sysEname+"]缓存的[sys_app_config]配置信息 end ********************************|");
                log.info("-");
                return confMap;
            }
        }
        log.info("从缓存["+spaceName+"]中，读取["+key+"]下的["+typeKey+"]类型配置失败！！！");
        return null;
    }
    /**
     * 删除本系统指定缓存key的内容
     * @param cacheKey 缓存key
     * @return
     */
    public static Object removeCache(String cacheKey){
        String spaceName = sysEname+"_"+cacheKey;
        Object object = SystemTools.getInstance().getCache(spaceName).removeCacheObject(cacheKey);
        return object;
    }

    /**
     * 本系统指定缓存key的内容是否存在
     * @param cacheKey 缓存key
     * @return
     */
    public static Object exsistCache(String cacheKey){
        String spaceName = sysEname+"_"+cacheKey;
        Object object = SystemTools.getInstance().getCache(spaceName).checkCacheObject(cacheKey);
        return object;
    }
    /**
     * 获取配置文件内容
     * @param key
     * @return
     */
    public static String getConfigVal(String key){
        String configVal = ConfigUtil.getInstance().getLocalByKey(file_config, key);
        return configVal;
    }


    private static Map<String,String> sendSmsByAppConfig(String mobile,String codeNo,Map<String,Object> appConfig_sms){
        Map<String,String> resultMap = new HashMap<String,String>();
        resultMap.put("requestId","");
        resultMap.put("bizId","");
        resultMap.put("code","fail");
        resultMap.put("message","服务端未找到短信服务商配置信息，请联系平台管理员！");
        if(appConfig_sms==null){
            return resultMap;
        }
        String sms_code_start = StrUtil.doNull(String.valueOf(((Map<String,String>)appConfig_sms.get("sms_code_start")).get("appValue")), "F");
        String sms_aliyun_accessKeyId = String.valueOf(((Map<String,String>)appConfig_sms.get("sms_aliyun_accessKeyId")).get("appValue"));
        String sms_aliyun_accessKeySecret = String.valueOf(((Map<String,String>)appConfig_sms.get("sms_aliyun_accessKeySecret")).get("appValue"));
        String sms_aliyun_signName = String.valueOf(((Map<String,String>)appConfig_sms.get("sms_aliyun_signName")).get("appValue"));
        String sms_aliyun_templateCode = String.valueOf(((Map<String,String>)appConfig_sms.get("sms_aliyun_templateCode")).get("appValue"));

        if(StrUtil.isNull(sms_aliyun_accessKeyId)){
            log.error("缓存中缺少[sms_aliyun_accessKeyId]配置信息");
            return resultMap;
        }
        if(StrUtil.isNull(sms_aliyun_accessKeySecret)){
            log.error("缓存中缺少[sms_aliyun_accessKeySecret]配置信息");
            return resultMap;
        }
        if(StrUtil.isNull(sms_aliyun_signName)){
            log.error("缓存中缺少[sms_aliyun_signName]配置信息");
            return resultMap;
        }
        if(StrUtil.isNull(sms_aliyun_templateCode)){
            log.error("缓存中缺少[sms_aliyun_templateCode]配置信息");
            return resultMap;
        }
        Map<String,String> param = new HashMap<>();
        param.put("sms_code_start",sms_code_start);
        param.put("sms_aliyun_accessKeyId",sms_aliyun_accessKeyId);
        param.put("sms_aliyun_accessKeySecret",sms_aliyun_accessKeySecret);
        param.put("sms_aliyun_signName",sms_aliyun_signName);
        param.put("sms_aliyun_templateCode",sms_aliyun_templateCode);
        param.put("mobile",mobile);
        param.put("codeNo",codeNo);

        resultMap = SmsUtil.sendSms(param);
        resultMap.put("sms_code_start",sms_code_start);
        return resultMap;
    }

    /**
     * 短信验证码发送（配置来自缓存）
     * @param mobile
     * @param codeNo
     * @return
     */
    public static Map<String,String>  sendSmsByCache(String mobile,String codeNo){
        Map<String,Object> appConfig_sms = (Map<String,Object>)getCacheByAppConfig("sms_aliyun");
        Map<String,String> resultMap = new HashMap<String,String>();
        resultMap.put("requestId","");
        resultMap.put("bizId","");
        resultMap.put("code","fail");
        resultMap.put("message","服务端未找到短信服务商配置信息，请联系平台管理员！");
        if(appConfig_sms==null){
            return resultMap;
        }
        resultMap = sendSmsByAppConfig(mobile,codeNo,appConfig_sms);
        return resultMap;
    }
    public static Map<String,String>  sendSmsByCache(String mobile,String codeNo,String sysEname) {
        Map<String, Object> appConfig_sms = (Map<String, Object>) getCacheByAppConfig("sms_aliyun",sysEname);
        Map<String,String> resultMap = new HashMap<String,String>();
        resultMap.put("requestId","");
        resultMap.put("bizId","");
        resultMap.put("code","fail");
        resultMap.put("message","服务端未找到短信服务商配置信息，请联系平台管理员！");
        if(appConfig_sms==null){
            return resultMap;
        }
        resultMap = sendSmsByAppConfig(mobile,codeNo,appConfig_sms);
        return resultMap;
    }
}
